/*
 *  main.cpp
 *  Created on: 2023-01-30
 *  Author: Tinker
 */

#include <iostream>
#include <sys/wait.h>
#include <stdlib.h>
#include "sys/mman.h"
#include "unistd.h"
#include <sys/system_properties.h>
#include <dlfcn.h>
#include "EagleLib.h"

#include "../shark/include/csr_types.h"
#include "../shark/include/Log.h"
#include <sched.h> //add new
using namespace std;
static pid_t shark_main_pid;

typedef struct shared_struct {
	bool_t reboot;
} shared_mem_t;

shared_mem_t * shared_mem = NULL;

bool_t get_reboot() {
	if (!shared_mem)
		return 0;
	LOGD("%s: %d", __FUNCTION__, shared_mem->reboot);
	return shared_mem->reboot;
}

/********************
 * vol : 默认为0
 *       1:重启自动连接
 *       2:重启不自动连接
 *       3:重启取消配对
 *       4:重启进入配对
 *       5:其他
 ********************/
void set_reboot(bool_t vol) {
	if (shared_mem)
		shared_mem->reboot = vol;
}

/* The actual main file */
void shark_main() {
	LOGD("AutoEagel business start");
	struct sched_param param;
    int maxPriority = sched_get_priority_max(SCHED_FIFO);
    param.sched_priority = maxPriority;//设置字段sched_priority的值
    if (sched_setscheduler(getpid(), SCHED_FIFO, &param) == -1)
    {
    	LOGD("sched_setscheduler() failed");
    }else{
    	LOGD("sched_setscheduler() succeed");
    }
	EagleLib_init();
	while (1) {
		sleep(1);
	}
}
int main(int argc, char** argv) {
	LOGD("AutoEagle main ...start>>>");
	LOGD("AutoEagle argc:%d",argc);
	if (3 == argc) {
		LOGD("argv[0] = [%d]%s argv[1] = [%d]%s argv[2] = [%d]%s\n",
				 strlen(argv[0]),argv[0], strlen(argv[1]),
				argv[1], strlen(argv[2]), argv[2]);
		if (strcmp(argv[1], "-c") == 0) {
			LOGD("sys.lynx.eagle.customer  %s\n", argv[2]);
			__system_property_set("sys.lynx.eagle.customer", argv[2]);
		}
	}
	shared_mem = static_cast<shared_mem_t *>(mmap(NULL, sizeof(*shared_mem),
			PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0));
	if (shared_mem == MAP_FAILED) {
		LOGD("mmap error");
		shared_mem = NULL;
	} else {
		memset(shared_mem, 0, sizeof(*shared_mem));
	}
	set_reboot(0);
	//here
#define SHARK_NO_FORK 0
#if !SHARK_NO_FORK
	if ((shark_main_pid = fork()) == 0) {
#endif
		shark_main();
		exit(0);
#if !SHARK_NO_FORK
	}
#endif
	LOGD("AutoEagel main...start monitor subprogress >>>");
	while (1) {
		pid_t pid = wait(NULL);
		sleep(1);
		if (pid == shark_main_pid) {
			LOGD("AutoEagel exit,restarting get_reboot = %d\n", get_reboot());
			if ((shark_main_pid = fork()) == 0) {
				LOGD("AutoEagle enforce fork \n");
				shark_main();
				enforce_process(0);
			}
		}
	}
	LOGD("AutoEagel main ...end<<<");
	return 0;
}
